package com.youmu.sichuansfc.filter;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.*;

/**
 *  测试环境 http请求 出入参 打印
 */
public class DevLoggerInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(DevLoggerInterceptor.class);


    /**
     * 在请求被处理之前进行调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        logger.info("进入拦截器");


        String path = request.getQueryString();
        if (path == null) {
            Map<String, String> map = new HashMap<String, String>();
            Enumeration headerNames = ((HttpServletRequest) request).getHeaderNames();
            while (headerNames.hasMoreElements()) {//循环遍历Header中的参数，把遍历出来的参数放入Map中
                String key = (String) headerNames.nextElement();
                String value = ((HttpServletRequest) request).getHeader(key);
                map.put(key, value);
            }
            System.out.println(map.toString());
            path = map.toString();
        }
        String url = request.getRequestURI();
        System.out.println("请求地址：[" + url + "]");

        // 输入数据流
        InputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str = null;

        List<Byte> input = new ArrayList<Byte>();
        byte[] buff = new byte[1];
        while ((is.read(buff)) > 0) {
            byte b = buff[0];
            input.add(b);
            if (b == (byte) '\n') {
                break;
            }
        }
        byte[] buffer = new byte[input.size()];
        int i = 0;
        for (byte b : input) {
            buffer[i++] = b;
        }
        str = new String(buffer).trim();
        System.out.println("输入流数据：[" + str + "]");
        return  true;
    }

    /**
     * 	在请求被处理之后进行调用
     * @param request
     * @param response
     * @param handle
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) throws  Exception{

        OutputStream os = response.getOutputStream();
        // HttpResponse rsp = (HttpResponse)response;
        // String  br = response.getOutputStream().toString();
        // System.out.println("输出流数据：[" + EntityUtils.toString(rsp.getEntity()) + "]");
        // System.out.println("输出流数据：[" + modelAndView + "]");
        // System.out.println("输出流数据：[" + new JSONObject(modelAndView.getModelMap()) + "]");
    }

    /**
     * 在请求结束之后才进行调用
     * @param request
     * @param response
     * @param object
     * @param exception
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception)
            throws Exception {
        System.out.println("EncodingInterceptor afterCompletion");
    }

}
